package mspbots.data.tl.prod.autotask.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.data.tl.base.AbstractBaseServiceImpl;
import mspbots.data.tl.entity.ResultEntity;
import mspbots.data.tl.prod.autotask.mapper.TaskAutotaskInformationMapper;
import mspbots.data.tl.prod.autotask.mapper.TaskAutotaskServiceCallsMapper;
import mspbots.data.tl.prod.autotask.model.TaskAutotaskInformation;
import mspbots.data.tl.prod.autotask.model.TaskAutotaskOpportunity;
import mspbots.data.tl.prod.autotask.model.TaskAutotaskServiceCalls;
import mspbots.data.tl.prod.autotask.service.TaskAutotaskServiceCallsService;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
@Log4j2
@RequiredArgsConstructor
@DS("master")
public class TaskAutotaskServiceCallsServiceImpl extends AbstractBaseServiceImpl<TaskAutotaskServiceCallsMapper,TaskAutotaskServiceCalls>
        implements TaskAutotaskServiceCallsService {

    private final TaskAutotaskInformationMapper taskAutotaskInformationMapper;

    @Override
    public void sync(ResultEntity content){
        log.info("Auto task ServiceCalls receiver content{}",content);
        JsonNode entity = content.getEntity();
        TaskAutotaskServiceCalls data=TaskAutotaskServiceCalls.builder()
                .serviceCallsId(super.getLongValue(entity.get("id")))
                .lastModifiedDateTime(ObjectUtils.isEmpty(entity.get("lastModifiedDateTime")) || "null".equalsIgnoreCase(entity.get("lastModifiedDateTime").asText()) ? null:LocalDateTime.parse(entity.get("lastModifiedDateTime").textValue(),DateTimeFormatter.ISO_OFFSET_DATE_TIME))
                .cancelationNoticeHours(ObjectUtils.isEmpty(entity.get("cancelationNoticeHours")) ? null : entity.get("cancelationNoticeHours").asDouble())
                .canceledByResourceId(super.getLongValue(entity.get("canceledByResourceID")))
                .canceledDateTime(ObjectUtils.isEmpty(entity.get("canceledDateTime")) || "null".equalsIgnoreCase(entity.get("canceledDateTime").asText()) ? null:LocalDateTime.parse(entity.get("canceledDateTime").textValue(),DateTimeFormatter.ISO_OFFSET_DATE_TIME))
                .companyId(super.getLongValue(entity.get("companyID")))
                .companyLocationId(super.getLongValue(entity.get("companyLocationID")))
                .createDateTime(ObjectUtils.isEmpty(entity.get("createDateTime")) || "null".equalsIgnoreCase(entity.get("createDateTime").asText()) ? null:LocalDateTime.parse(entity.get("createDateTime").textValue(),DateTimeFormatter.ISO_OFFSET_DATE_TIME))
                .creatorResourceId(super.getLongValue(entity.get("creatorResourceID")))
                .description(ObjectUtils.isEmpty(entity.get("description")) ? null : entity.get("description").asText())
                .duration(ObjectUtils.isEmpty(entity.get("duration")) ? null : entity.get("duration").asDouble())
                .endDateTime(ObjectUtils.isEmpty(entity.get("endDateTime")) || "null".equalsIgnoreCase(entity.get("endDateTime").asText()) ? null:LocalDateTime.parse(entity.get("endDateTime").textValue(),DateTimeFormatter.ISO_OFFSET_DATE_TIME))
                .impersonatorCreatorResourceId(super.getLongValue(entity.get("impersonatorCreatorResourceID")))
                .isComplete(ObjectUtils.isEmpty(entity.get("isComplete")) ? null : entity.get("isComplete").asInt())
                .lastModifiedDateTime(ObjectUtils.isEmpty(entity.get("lastModifiedDateTime")) || "null".equalsIgnoreCase(entity.get("lastModifiedDateTime").asText()) ? null:LocalDateTime.parse(entity.get("lastModifiedDateTime").textValue(),DateTimeFormatter.ISO_OFFSET_DATE_TIME))
                .startDateTime(ObjectUtils.isEmpty(entity.get("startDateTime")) || "null".equalsIgnoreCase(entity.get("startDateTime").asText()) ? null:LocalDateTime.parse(entity.get("startDateTime").textValue(),DateTimeFormatter.ISO_OFFSET_DATE_TIME))
                .status(ObjectUtils.isEmpty(entity.get("status")) ? null : entity.get("status").asInt())
                .syncTime(LocalDateTime.now())
                .build();
        data.setTenantCode(content.getTenantId());
        setNameInfo(data);

        TaskAutotaskServiceCalls dbData = super.baseMapper.selectOne(Wrappers.<TaskAutotaskServiceCalls>lambdaQuery()
                .eq(TaskAutotaskServiceCalls::getTenantCode, data.getTenantCode())
                .eq(TaskAutotaskServiceCalls::getServiceCallsId, data.getServiceCallsId())
                .last("limit 1"));
        if (ObjectUtils.isEmpty(dbData)){
            super.baseMapper.insert(data);
        } else {
            data.setId(dbData.getId());
            super.baseMapper.updateById(data);
        }
    }

    private void setNameInfo(TaskAutotaskServiceCalls data) {
        List<TaskAutotaskInformation> informationList = taskAutotaskInformationMapper.selectList(Wrappers.<TaskAutotaskInformation>lambdaQuery()
                .eq(TaskAutotaskInformation::getTenantCode, data.getTenantCode())
                .eq(TaskAutotaskInformation::getType,"ServiceCalls")
                .in(TaskAutotaskInformation::getName, List.of("Status")));
        if (!CollectionUtils.isEmpty(informationList)) {
            informationList.forEach(information -> {
                if (!ObjectUtils.isEmpty(data.getStatus())
                        && "Status".equalsIgnoreCase(information.getName())
                        && data.getStatus().toString().equals(information.getValue())) {
                    data.setStatusName(information.getLabel());
                }
            });
        }
    }

}
